<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="所属分组">
        <el-select v-model="queryParams.teamId" placeholder="请选择所属分组">
          <el-option
            v-for="dict in teamOptions"
            :key="dict.id"
            :label="dict.teamName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="事件名称" prop="eventTypeName">
        <el-input
          v-model="queryParams.eventTypeName"
          placeholder="请输入事件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否启用" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['config:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['config:type:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['config:type:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="handleExport"
        v-hasPermi="['config:type:export']"
      >导出</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="typeList"
              :default-sort = "{prop: 'eventType', order: 'ascending'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="编号" width="55" align="center"/>
      <el-table-column label="事件分组" align="center" prop="teamName" :formatter="teamFormat"/>
      <el-table-column label="虚拟事件名" align="center" prop="eventType"  sortable />
      <el-table-column label="虚拟事件显示名" align="center" prop="eventTypeName" />
      <el-table-column label="标签" align="center" prop="tags" />
      <el-table-column label="事件截图" align="center" prop="eventImg" />
      <el-table-column label="包含事件" align="center" prop="includeEvent" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="是否启用" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['config:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['config:type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer
      title="创建虚拟事件"
      :visible.sync="open"
      size="50%">
      <div class="data-tip">虚拟事件可以组合多个事件和筛选条件，以方便您灵活的使用各种分析模型</div>
      <div style="padding:20px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="所属分组" prop="teamId">
            <el-select v-model="form.teamId" placeholder="请选择所属分组">
              <el-option
                v-for="dict in teamOptions"
                :key="dict.id"
                :label="dict.teamName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="事件名称" prop="eventTypeName">
            <el-input v-model="form.eventTypeName" placeholder="请输入事件名称" />
          </el-form-item>
          <el-form-item label="事件编码" prop="eventType">
            <el-input v-model="form.eventType" placeholder="请输入事件编码" />
          </el-form-item>
          <el-form-item label="标签">
            <el-tag
              :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag}}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
          </el-form-item>
          <el-form-item label="事件截图：" prop="logo">
            <image-upload v-model="form.eventImg" :limit="1"/>
          </el-form-item>
          <el-form-item label="事件备注" prop="sortName">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入事件备注" />
          </el-form-item>
          <h5 style="font-size:14px;font-weight:500;line-height:10px;"><span style="color: red;">* </span><span>虚拟事件的组成</span></h5>
            <div style="font-size:12px;color:#8492a6;margin-bottom:10px;">当以下事件中任意一个被触发时，视作该虚拟事件被触发</div>
          <el-row :gutter="10" v-for="(eventType,index) in form.eventTypesArray">
            <el-form-item label="" prop="status">
              <el-popover
                placement="bottom-start"
                width="800"
                trigger="click"
              >
                <PanelSelect ref="panelSelect" @selected="selected" :eventObj="eventType"/>
                <el-input slot="reference" v-model="eventType.eventTypeName" placeholder="点击选择事件" readonly
                          style="width: 200px;" suffix-icon="el-icon-arrow-down">
                </el-input>
              </el-popover>
              <el-link type="primary" :underline="false" style="padding-left:20px;" @click="addRule(eventType)">
                <i class="el-icon-plus"></i> <span class="innerContent">触发限制条件</span>
              </el-link>
            </el-form-item>
            <el-form-item label="" style="display: block;padding-left:80px;" label-width="60px">
              <AndLine style="height: calc(100% - 10px);" v-show="eventType.eventItems.length>1" v-model="eventType.beginConditionRelation"></AndLine>
              <p style="margin: 0 0 10px;" v-for="(eventItem,index) in eventType.eventItems">
                <el-select v-model="eventItem.eventType" style="width:120px;margin-right: 10px;"
                           @change="eventTypeChange(eventItem.eventType,index)">
                  <el-option
                    v-for="dict in eventTypeOptions"
                    :key="dict.id"
                    :label="dict.eventTypeName"
                    :value="dict.id"
                  />
                </el-select>
                <el-select v-model="eventItem.eventItem" style="width:120px;margin-right: 10px;"  value-key="id">
                  <el-option
                    v-for="dict in allEventItemListOpts[eventItem.eventType]"
                    :key="dict.id"
                    :label="dict.eventItemName"
                    :value="dict"
                  />
                </el-select>
                <el-select v-model="eventItem.eventItemExpression" style="width:120px;margin-right: 10px;">
                  <el-option
                    v-for="dict in  eventPropertysOptions[eventItem.eventItem.valueType]"
                    :key="dict.id"
                    :label="dict.eventItemExpression"
                    :value="dict.eventItemCode"
                  />
                </el-select>
                <el-input v-model="eventItem.value1Str" type="text" controls-position="right" style="width:100px"
                          v-show="eventItem.eventItemExpression!='between'"></el-input>
                <span v-show="eventItem.eventItemExpression=='between'">
                <el-input v-model="eventItem.value1Str" type="text" controls-position="right"
                          style="width:90px"></el-input>与
                <el-input v-model="eventItem.value2Str" type="text" controls-position="right"
                          style="width:90px"></el-input>之间
            </span>
                <el-link type="primary" :underline="false" style="padding-left:20px;font-size:18px"
                         @click="removeRule(form.eventTypes,index)">
                  <i class="el-icon-remove"></i>
                </el-link>
              </p>
            </el-form-item>
          </el-row>

          <el-row class="bottomLine">
            <div style="line-height:30px;">
              <el-link :underline="false" @click="addBussinssLine"><span class="index_letterJar_2bEZs">+ </span>指标</el-link>
            </div>
          </el-row>
          <el-form-item label="是否启用" prop="status">
            <el-select v-model="form.status" placeholder="请选择是否启用">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="float:right">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType, exportType } from "@/api/config/type";
import {eventTeamDataFun} from "@/api/config/eventteam";
import {allEventItemsOptions, eventTypeOptions} from "@/api/config/item";
import {listAllPropertyResult} from "@/api/config/property";
import {getAllEventMethodResult} from "@/api/config/emethod";
import PanelSelect from "@/components/PanelSelect";
import AndLine from '@/components/AndLine/index.vue'
export default {
  name: "virtualevent",
  components: {
    PanelSelect,AndLine
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 事件类型表格数据
      typeList: [],
      allEventItemListOpts:{},
      eventPropertysOptions:{},
      eventTypeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否启用字典
      statusOptions: [],
      teamOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamCode:undefined,
        eventTypeName: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        eventTypesArray:[],
        eventJson:null,
        tags:null
      },
      // 表单校验
      rules: {
        teamId: [
          { required: true, message: "请选择事件分组", trigger: "blur" }
        ],
        eventTypeName: [
          { required: true, message: "事件名称不能为空", trigger: "blur" }
        ],
        eventType: [
          { required: true, message: "事件编码不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "事件状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getAllEventItemsList();
    this.getEventTypeList();
    this.getList();
    this.getEventTeamList();
    this.getDicts("sys_yes_no").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询事件类型列表 */
    getList() {
      this.loading = true;
      this.queryParams.categoryType='virtual';
      listType(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getEventTypeList() {
      var param = {status: 'Y'};
      eventTypeOptions(param).then(response => {
        this.eventTypeOptions = response.data;
      });
    },

    getAllEventItemsList(){
      allEventItemsOptions().then(response => {
        this.allEventItemListOpts = response.data;
      });
      listAllPropertyResult().then(response => {
        this.eventPropertysOptions = response.data;
      });
      getAllEventMethodResult().then(response => {
        this.allEventItemMethodOpts = response.data;
      });
    },

    getEventTeamList(){
      var param={status:'Y'};
      eventTeamDataFun(param).then(response => {
        this.teamOptions = response.data;
      });
    },
    // 是否启用字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    teamFormat(row, column) {
      var teamName='';
      for(var i=0;i<this.teamOptions.length;i++){
        if(this.teamOptions[i].id==row.teamId){
          teamName=this.teamOptions[i].teamName;
          break;
        }
      }
      return teamName;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        eventType: undefined,
        eventTypeName: undefined,
        eventImg: undefined,
        remark: undefined,
        eventTypesArray:[],
        eventJson: undefined,
        tags: undefined,
        status: 'Y',
        teamId: undefined,
        includeEvent: undefined,
        categoryType: 'virtual'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加事件类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getType(id).then(response => {
        this.form = response.data;
        this.form.eventTypesArray=JSON.parse(this.form.eventJson);
        this.dynamicTags=this.form.tags?this.form.tags.split(','):[];
        this.open = true;
        this.title = "修改事件类型";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.eventJson=JSON.stringify(this.form.eventTypesArray);
          let includeEvent='';
          this.form.eventTypesArray.forEach(event=>{
            if(includeEvent){
              includeEvent=includeEvent+','+event.eventTypeName;
            }else{
              includeEvent=event.eventTypeName;
            }
          })
          this.form.includeEvent=includeEvent;
          this.form.tags=this.dynamicTags?this.dynamicTags.join(","):'';
          if (this.form.id != undefined) {
            updateType(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            this.form.categoryType= 'virtual';
            addType(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除事件类型编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delType(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有事件类型数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportType(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    addRule(eventType){
      let eventItem={
        eventType:'',
        eventItem:{},
        eventItemExpression:'',
        valueType:'',
        value1Str:'',
        value2Str:'',
      };
      eventType.eventItems.push(eventItem);
    },

    removeRule(array,index){
      array.splice(index,1);
    },
    eventTypeChange(array,index){
      array[index].eventItem={};
      array[index].eventItemExpression='';
      array[index].value1Str='';
      array[index].value2Str='';
    },
    addBussinssLine(){
        let eventType={
           eventType:null,
           eventTypeName:null,
           eventItems:[]
        };
        this.form.eventTypesArray.push(eventType)
    },

    selected(item,eventItem) {
      eventItem.eventTypeName = item.eventTypeName;
      eventItem.eventType=item.eventType;
      eventItem.typeId=item.id;
    },
  }
};
</script>
<style>
.data-tip {
  background: #fff8ea;
  color: #475669;
  font-size: 12px;
  line-height: 1.5;
  padding: 8px 24px;
  font-weight: 400;
  z-index: 1;
  position: relative;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.bottomLine {
  width: 100%;
  display: inline-block;
  border-bottom: 1px solid #e9f0f7;
  margin-bottom: 10px;
  padding-bottom: 10px;
}

.index_letterJar_2bEZs {
  border-radius: 100%;
  display: inline-block;
  width: 20px;
  height: 20px;
  background: #04cb94;
  line-height: 20px;
  font-size: 12px;
  margin: 0 8px 0 6px;
  color: #fff;
  text-align: center;
}
</style>
